package com.xj.shop.manage.all.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xj.shop.manage.all.mapper.GoodsSpecsMapper;
import com.xj.shop.manage.all.model.dto.GoodsSpecsDTO;
import com.xj.shop.manage.all.model.entity.GoodsSpecs;
import com.xj.shop.manage.all.model.vo.GoodsSpecsVO;
import com.xj.shop.manage.all.service.GoodsSpecsService;
import io.github.wslxm.springbootplus2.core.base.service.impl.BaseServiceImpl;
import io.github.wslxm.springbootplus2.core.utils.BeanDtoVoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 商品表 ServiceImpl
 *
 * <p>
 * ::本代码由[兮家小二]提供的代码生成器生成,如有问题,请手动修改 ::作者CSDN:https://blog.csdn.net/qq_41463655
 * </p>
 * @author ws
 * @email 1720696548@qq.com
 * @date 2022-08-24 18:54:43
 */
@Service
public class GoodsSpecsServiceImpl extends BaseServiceImpl<GoodsSpecsMapper, GoodsSpecs> implements GoodsSpecsService {


    @Override
    public List<GoodsSpecsVO> findByGoodsId(String goodsId) {
        List<GoodsSpecs> list = this.list(new LambdaQueryWrapper<GoodsSpecs>()
                .eq(GoodsSpecs::getGoodsId, goodsId)
                .orderByAsc(GoodsSpecs::getCreateTime)
        );
        return BeanDtoVoUtil.listVo(list, GoodsSpecsVO.class);
    }


    @Override
    public boolean updGoodsSpecsBatch(List<GoodsSpecsDTO> dtos, String goodsId) {
        if (dtos == null || dtos.size() == 0) {
            return false;
        }
        List<GoodsSpecsVO> goodsSpecsList = findByGoodsId(goodsId);
        List<String> goodsSpecsIds = goodsSpecsList.stream().map(GoodsSpecsVO::getId).collect(Collectors.toList());

        //
        List<GoodsSpecs> addGoodsSpecses = new ArrayList<>();
        List<GoodsSpecs> updGoodsSpecses = new ArrayList<>();
        List<String> delGoodsSpecsIds = goodsSpecsIds;
        for (GoodsSpecsDTO dto : dtos) {
            if (StringUtils.isBlank(dto.getId())) {
                // 新增
                GoodsSpecs goodsSpecs = BeanDtoVoUtil.convert(dto, GoodsSpecs.class);
                goodsSpecs.setGoodsId(goodsId);
                addGoodsSpecses.add(goodsSpecs);
            } else if (goodsSpecsIds.contains(dto.getId())) {
                // 编辑
                updGoodsSpecses.add(BeanDtoVoUtil.convert(dto, GoodsSpecs.class));
                delGoodsSpecsIds.remove(dto.getId());
            }
        }
        if (addGoodsSpecses.size() > 0) {
            this.saveBatch(addGoodsSpecses);
        }
        if (updGoodsSpecses.size() > 0) {
            this.updateBatchById(updGoodsSpecses);
        }
        if (delGoodsSpecsIds.size() > 0) {
            this.removeByIds(delGoodsSpecsIds);
        }
        return true;
    }
}
